package user

import (
	"context"
	"net/http"

	"go-zero-admin/apps/system/cmd/api/internal/svc"
	"go-zero-admin/apps/system/cmd/api/internal/types"
	"go-zero-admin/apps/system/cmd/rpc/syspb"
	"go-zero-admin/pkg/ctxdata"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetUserMenusLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	r      *http.Request
}

func NewGetUserMenusLogic(ctx context.Context, svcCtx *svc.ServiceContext, r *http.Request) *GetUserMenusLogic {
	return &GetUserMenusLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		r:      r,
	}
}

func (l *GetUserMenusLogic) GetUserMenus(req *types.GetUserMenusReq) (resp *types.GetUserMenusResp, err error) {
	// 获取用户菜单数据
	menuListResp, err := l.svcCtx.UserRpc.GetUserRules(l.ctx, &syspb.GetUserRulesReq{Id: ctxdata.GetUidFromCtx(l.ctx)})
	if err != nil {
		return nil, err
	}

	menuTrees := menuListResp.GetTree()
	if len(menuTrees) == 0 {
		menuTrees = make([]*syspb.SysMenuTree, 0)
	}
	permissions := menuListResp.GetPermissions()
	if len(permissions) == 0 {
		permissions = []string{}
	}

	return &types.GetUserMenusResp{
		MenuList:    l.GetUserMenuTree(menuTrees),
		Permissions: permissions,
	}, nil
}

// GetUserMenuTree 处理菜单数据
func (l *GetUserMenusLogic) GetUserMenuTree(rpcMenuTreeList []*syspb.SysMenuTree) []*types.UserMenuTree {
	menuTreeList := make([]*types.UserMenuTree, 0)

	for _, rpcMenu := range rpcMenuTreeList {
		menuTree := &types.UserMenuTree{
			UserMenu: &types.UserMenu{
				Id:        rpcMenu.GetMenu().GetId(),
				Pid:       rpcMenu.GetMenu().GetPid(),
				Name:      rpcMenu.GetMenu().GetName(),
				Component: rpcMenu.GetMenu().GetComponent(),
				Path:      rpcMenu.GetMenu().GetPath(),
				Meta: &types.MenuMeta{
					Icon:        rpcMenu.GetMenu().GetIcon(),
					Title:       rpcMenu.GetMenu().GetTitle(),
					IsLink:      "",
					IsHide:      rpcMenu.GetMenu().GetIsHide() == 1,
					IsKeepAlive: rpcMenu.GetMenu().GetIsKeepAlive() == 1,
					IsAffix:     rpcMenu.GetMenu().GetIsAffix() == 1,
					IsIframe:    rpcMenu.GetMenu().GetIsIframe() == 1,
				},
			},
		}
		if rpcMenu.GetMenu().GetIsIframe() == 1 || rpcMenu.GetMenu().GetIsLink() == 1 {
			menuTree.UserMenu.Meta.IsLink = rpcMenu.GetMenu().GetLinkUrl()
		}

		if len(rpcMenu.GetChildren()) > 0 {
			childrenTreeList := l.GetUserMenuTree(rpcMenu.GetChildren())
			menuTree.Children = childrenTreeList
		}

		menuTreeList = append(menuTreeList, menuTree)
	}
	return menuTreeList
}
